//
//  PageContro.m
//  AdImage
//
//  Created by Burn on 2019/7/23.
//  Copyright © 2019 menksoft. All rights reserved.
//

#import "PageContro.h"

@interface PageContro ()

@property(strong,nonatomic) UILabel *lastTimePage;
@property(assign,nonatomic) CGFloat pageW;
@property(assign,nonatomic) CGFloat pageSpacing;
@property(strong,nonatomic) NSMutableArray *pageArray;

@end

@implementation PageContro

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.pageW = 8;
        self.pageSpacing = 3;
        self.pageIndicatorTintColor = [UIColor lightGrayColor];
        self.currentPageIndicatorTintColor = [UIColor orangeColor];
        self.hidesForSinglePage = YES;
    }
    return self;
}

- (void)addSubViews{
    CGFloat x = 0;
    CGFloat w = 0;
    switch (self.location) {
        case LocationCenter:
            w = self.numberOfPages * self.pageW + (self.numberOfPages - 1) * self.pageSpacing;
            x = self.frame.size.width * 0.5 - w / 2;
            break;
        case LocationLeft:
            x = 10;
            break;
        case LocationRight:
            w = self.numberOfPages * self.pageW + (self.numberOfPages - 1) * self.pageSpacing;
            x = self.frame.size.width - w - 10.0;
            break;
            
        default:
            break;
    }
    
    for (int i = 0; i < self.pageArray.count; i++) {
        UILabel *label = self.pageArray[i];
        [label removeFromSuperview];
    }
    
    for (int i = 0; i < self.numberOfPages; i++) {
        UILabel *page = [[UILabel alloc]initWithFrame:CGRectMake(x + i * self.pageW + i * self.pageSpacing, 0, self.pageW, 2)];
        page.tag = 1000 + i;
        page.backgroundColor = self.pageIndicatorTintColor;
        [self addSubview:page];
        
        [self.pageArray addObject:page];
    }
    
}

- (void)setCurrent{
    if (self.lastTimePage) {
        self.lastTimePage.backgroundColor = self.pageIndicatorTintColor;
    }
    
    UIView *view =  [self viewWithTag:1000 + self.currentPage];
    if (view) {
        view.backgroundColor = self.currentPageIndicatorTintColor;
        self.lastTimePage = (UILabel *)view;
    }
    
}

- (void)setCurrentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor{
    _currentPageIndicatorTintColor = currentPageIndicatorTintColor;
}

- (void)setPageIndicatorTintColor:(UIColor *)pageIndicatorTintColor{
    _pageIndicatorTintColor = pageIndicatorTintColor;
}

- (void)setCurrentPage:(NSInteger)currentPage{
    _currentPage = currentPage;
    [self setCurrent];
}

- (void)setNumberOfPages:(NSInteger)numberOfPages{
    _numberOfPages = numberOfPages;
    [self addSubViews];
    [self setCurrent];
}

- (NSMutableArray *)pageArray{
    if (!_pageArray) {
        _pageArray = [NSMutableArray array];
    }
    return _pageArray;
}

@end
